package service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import beans.Customer;
import beans.Info;
import dao.DAO;

public class CustomerService {
	public static final int PERPAGE = 15; // 分页每页显示条数
	private DAO<Customer> dao;

	public CustomerService() {
		dao = new DAO<>(Customer.class);
	}

	public Info<Customer> getCustomerById(String id) {
		Info<Customer> info = new Info<>();
		info.count = 1L;
		info.list = new ArrayList<>();
		info.list.add(dao.getById(Integer.parseInt(id)));
		return info;
	}

	public Customer getCustomerByWechat(String wechat) {
		String hql = "from Customer where wechat='"+wechat+"'";
		try {
			Customer customer = (Customer) dao.getFromHQL(hql, 0, 1).get(1L).get(0);
			return customer;
		}catch (Exception e) {
			return null;
		}
	}

	public Info<Customer> getCustomer(String page) {
		int startP = (Integer.parseInt(page) - 1) * PERPAGE; // 分页开始条数
		Map<Long, List<Customer>> map = dao.getAll(startP, PERPAGE);
		Info<Customer> info = new Info<>();
		info.count = map.keySet().iterator().next();
		info.list = map.values().iterator().next();
		return info;
	}

	public void deleteById(String id) {
		dao.delById(Integer.parseInt(id));
	}

	public void alterCustomer(String cid, String username, String sex, String money, String tel, String addr,
			String school, String wechat) {
		String sql = "update Customer set username='" + username + "', sex='" + sex + "', money=" + money + ", tel='"
				+ tel + "', addr='" + addr + "', school='" + school + "', wechat='" + wechat + "' where id=" + cid;
		dao.updateSQL(sql);
	}

	/**
	 * 注册用户
	 * 
	 * @param username
	 * @param sex
	 * @param tel
	 * @param addr
	 * @param money
	 * @param school
	 * @param wechat
	 */
	public Customer registerUser(String username, String sex, String tel, String addr, String money, String school,
			String wechat) {
		Customer customer = new Customer(0, username, sex, tel, addr, Double.parseDouble(money), school, wechat);
		dao.add(customer);
		return customer;
	}
}
